package com.rainsoftware.LicenseSystem.services;

import com.rainsoftware.LicenseSystem.models.entity.KeyPair;
import com.rainsoftware.LicenseSystem.utils.StandardResponse;
import gaarason.database.contract.eloquent.Record;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

@Service
public class KeypairService {

    private final KeyPair.Model keypairModel;

    @Autowired
    UserService userService;

    public KeypairService(KeyPair.Model keypairModel) {
        this.keypairModel = keypairModel;
    }

    public StandardResponse getPublicKey() {
        try {
            Record<KeyPair, Integer> record = keypairModel.newQuery().where("developer_id", userService.getSystemUser().getId()).first();
            if (record == null) {
                return new StandardResponse(false, HttpStatus.NOT_FOUND, "Key pair not found.", null);
            }
            KeyPair keyPair = record.getEntity();
            // Return public key as Base64 encoded string
            return new StandardResponse(true, HttpStatus.OK, "Public key retrieved successfully.",
                    new JSONObject().put("id", keyPair.getId())
                            .put("public_key", keyPair.getPrivKey()));
        } catch (Exception e) {
            return new StandardResponse(false, HttpStatus.INTERNAL_SERVER_ERROR, "Unable to retrieve public key, internal server error.", null);
        }
    }
}